package com.th.apicenter.vivo;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.th.apicenter.config.ThLog;
import com.th.apicenter.mapper.ThVIVODataMapper;
import com.th.apicenter.tools.ThResult;
import com.th.apicenter.tools.ThTools;
import com.th.apicenter.vivo.dto.VIVOExcelDTO;
import com.th.apicenter.vivo.entity.ThVivoData;
import com.th.apicenter.vivo.service.VIVOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/vivo")
@Slf4j
public class VIVOController {

    @Autowired
    private VIVOService vivoService;

    @Autowired
    private ThVIVODataMapper thVIVODataMapper;

    /**
     * https://vivo.tinghongzz.com/clickjs?srcId=ds-202502172752&os=__OS__&imei=__IMEI__&
     * ip=__IP__&oaid=__OAID__&androidid=__ANDROIDID__&requestid=__REQUESTID__&
     * requesttime=__REQUESTTIME__&advertiserid=__ADVERTISERID__&creativeid=__CREATIVEID__&
     * ts=__TS__
     */
    @GetMapping("/monitor")
    @ThLog(value = "接收VIVO的检测数据", type = "vivo", trackTime = true)
    public ThResult receiveUrl(@RequestParam(name = "srcId", required = false) String srcId,
                                @RequestParam(name = "os", required = false) String os,
                                @RequestParam(name = "imei", required = false) String imei,
                                @RequestParam(name = "ip", required = false) String ip,
                                @RequestParam(name = "oaid", required = false) String oaid,
                                @RequestParam(name = "androidid", required = false) String androidid,
                                @RequestParam(name = "requestid", required = false) String requestid,
                                @RequestParam(name = "requesttime", required = false) String requesttime,
                                @RequestParam(name = "advertiserid", required = false) String advertiserid,
                                @RequestParam(name = "creativeid", required = false) String creativeid,
                                @RequestParam(name = "ts", required = false) String ts) {
        ThResult ThResult = new ThResult();
        ThVivoData thVivoData = new ThVivoData();
        thVivoData.setSrcId(ThTools.isNull(srcId) ? "" : srcId);
        thVivoData.setAccountId(ThTools.isNull(srcId) ? "" : srcId);
        thVivoData.setOs(ThTools.isNull(os) ? "" : os);
        thVivoData.setImei(ThTools.isNull(imei) ? "" : imei);
        thVivoData.setIp(ThTools.isNull(ip) ? "" : ip);
        thVivoData.setOaid(ThTools.isNull(oaid) ? "" : oaid);
        thVivoData.setAndroidid(ThTools.isNull(androidid) ? "" : androidid);
        thVivoData.setRequestid(ThTools.isNull(requestid) ? "" : requestid);
        thVivoData.setRequesttime(ThTools.isNull(requesttime) ? "" : requesttime);
        thVivoData.setAdvertiserid(ThTools.isNull(advertiserid) ? "" : advertiserid);
        thVivoData.setCreativeid(ThTools.isNull(creativeid) ? "" : creativeid);
        thVivoData.setTs(ThTools.isNull(ts) ? "" : ts);
        try {
            vivoService.monitor(thVivoData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ThResult;
    }

    @GetMapping("/exportData")
    public void exportData(HttpServletResponse response,
                           @RequestParam(name = "adid", required = false) String adid,
                           @RequestParam(name = "time", required = false) String time,
                           @RequestParam(name = "type", required = false) Integer type) {
        String startTime = time + " 00:00:00";
        String endTime = time + " 23:59:59";
        List<VIVOExcelDTO> vivoExcelDTOList = thVIVODataMapper.queryDataByExcel(adid, startTime, endTime, type);
        ExcelWriter writer = ExcelUtil.getWriter(true); // true 表示使用 xlsx 格式
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("vivo数据.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 写入数据（自动识别 @Alias 注解生成表头）
            writer.write(vivoExcelDTOList, true);
            // 将 Excel 流写入响应
            writer.flush(response.getOutputStream(), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            response.reset(); // 清空已写入的数据
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
